/**
 * Copyright: Copyright (c) 2012
 * Company:anhosi.com
 * @author lifuyu
 * @date Aug 20, 2012
 * @version V1.0
 *
 * @Description: 
 */
package com.microcm.manage.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.microcm.common.BeanUtils;
import com.microcm.common.CUtils;
import com.microcm.insync.service.InsyncService;
import com.microcm.manage.dao.SuperDao;
import com.microcm.manage.entity.Goods;
import com.microcm.manage.entity.SyncShop;
import com.microcm.manage.service.SuperService;
import com.microcm.system.entity.SysConfig;
import com.microcm.system.entity.SysMenu;
import com.microcm.system.entity.TagMenu;
import com.microcmframework.core.entity.PageBean;
import com.taobao.api.domain.Shop;

/**
 * 管理通用操作类
 * 
 * @author kansum
 * 
 */
@Service("superService")
public class SuperServiceImpl implements SuperService
{
	@Autowired
	private SuperDao superDao;

	@Autowired
	private InsyncService insyncService;

	/**
	 * 保存选择的淘宝类别数据到本地库
	 * 
	 * @author：lifuyu
	 * 
	 * @param catList
	 * @return
	 */
	public String saveCategory(List<?> catList)
	{
		boolean ret = this.superDao.batchCategorySave(catList);
		return ret ? "1" : "0";
	}

	/**
	 * 删除本地的类别数据以及旗下的子类别数据
	 * 
	 * @author：lifuyu
	 * 
	 * @param cid
	 * @return
	 */
	public String deleteCategory(Long cid)
	{
		List<Long> cidLs = new ArrayList<Long>();
		deepGetCidForDel(cid, cidLs);
		cidLs.add(cid);
		boolean ret = this.superDao.batchCategoryDelete(cidLs);
		return ret ? "1" : "0";
	}

	private void deepGetCidForDel(long parentCid, List<Long> cidLs)
	{
		// 查询子类别
		List<?> qryLs = this.superDao.queryList("manage.queryCategory", parentCid);
		if (CUtils.isEmpty(qryLs))
			return;

		for (Object o : qryLs)
		{
			Map<?, ?> cm = (Map<?, ?>) o;

			Long cid = (Long) cm.get("cid");
			boolean isParent = (Long) (cm.get("sic")) > 0;
			if (isParent)
				deepGetCidForDel(cid, cidLs);
			cidLs.add(cid);
		}
	}

	/**
	 * 查询所有本地的类别
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String queryCategory(long parentCid, List<Map<String, Object>> resultList)
	{
		List<?> qryLs = this.superDao.queryList("manage.queryCategory", parentCid);
		if (CUtils.isEmpty(qryLs))
			return "0";

		for (Object o : qryLs)
		{
			Map<?, ?> cm = (Map<?, ?>) o;

			Map<String, Object> m = new HashMap<String, Object>();

			m.put("id", cm.get("cid"));
			m.put("text", cm.get("name"));
			boolean isParent = (Long) (cm.get("sic")) > 0;
			if (isParent)
				m.put("state", "closed");
			else
				m.put("state", "open");

			Map<String, Object> attrM = new HashMap<String, Object>();
			attrM.put("isParent", isParent);
			attrM.put("parentCid", cm.get("parentCid"));
			attrM.put("sortOrder", cm.get("sno"));
			m.put("attributes", attrM);
			resultList.add(m);
		}
		return "1";
	}

	/**
	 * 添加TAG
	 * 
	 * @param mnid
	 * @param tagName
	 * @return
	 */
	public String saveTag(String mnid, String v_tagName)
	{
		String[] tagNames = v_tagName.split(",");
		for (String tagName : tagNames)
		{
			if ((Integer) this.superDao.queryObject("manage.isTagExist", tagName) > 0)
			{
				return "EXIST";
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("mnid", mnid);
			map.put("tagName", tagName);

			this.superDao.insertObject("manage.insertTag", map);
		}
		return "OK";
	}

	/**
	 * 保存商品信息
	 * 
	 * @author：lifuyu
	 * 
	 * @param numIid
	 * @param goodsParam
	 * @return
	 */
	public String saveGoods(long numIid, Map<String, String> gp)
	{
		String n_tags = gp.get("tags");
		String o_tags = null;
		Goods goods = null;
		Object o = this.superDao.queryObject("manage.getSingleGoods", numIid);
		if (o == null)
			goods = new Goods();
		else
		{
			goods = (Goods) o;
			o_tags = goods.getTags();
		}
		try
		{
			BeanUtils.copyAnyProps(gp, goods, null, true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return e.getMessage();
		}
		if (CUtils.isNotEmpty(o_tags) && CUtils.isNotEmpty(n_tags))
		{
			String[] tagNames = n_tags.split(",");
			for (String tagName : tagNames)
			{
				if (o_tags.indexOf(tagName) == -1)
					o_tags += "," + tagName;
			}
			goods.setTags(o_tags);
		}

		// 将索引标记置为0，那么将会被从新被索引
		goods.setModifyTm(new Date());
		goods.setIdx(0);

		// 保存商品信息
		if (o == null)
			this.superDao.insertObject("manage.insertGoods", goods);
		else
			this.superDao.updateObject("manage.updateGoods", goods);

		// 收集商品对应的店铺信息
		collectedShop(goods.getNick(), goods.getSellerCreditScore());

		return "1";
	}

	/**
	 * 收集商品对应的店铺信息 如果还没有收集，那么调用接口返回店铺信息
	 * 
	 * @author：lifuyu
	 * @param nick
	 * @param sellerCreditScore
	 */
	private void collectedShop(String nick, Long sellerCreditScore)
	{
		if ((Integer) this.superDao.queryObject("manage.existShop", nick) > 0)
			return;
		Shop shop = insyncService.getShopFromTaobao(nick);
		if (shop == null)
			return;
		SyncShop syncShop = new SyncShop();
		try
		{
			BeanUtils.copyAnyProps(shop, syncShop, null, true);
			BeanUtils.copyAnyProps(shop.getShopScore(), syncShop, null, true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return;
		}
		syncShop.setSellerCreditScore(sellerCreditScore);
		syncShop.setModifyTm(new Date());
		syncShop.setIdx(0);
		syncShop.setStatus(1);
		this.superDao.insertObject("manage.insertShop", syncShop);
	}

	/**
	 * 从DB中查询菜单
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String queryMenusByPmnid(int pmnid, List<Map<String, Object>> resultList)
	{
		List<?> qryLs = this.superDao.queryList("system.queryMenusByPmnid", pmnid);
		if (CUtils.isEmpty(qryLs))
			return "0";

		for (Object o : qryLs)
		{
			Map<?, ?> cm = (Map<?, ?>) o;

			Map<String, Object> m = new HashMap<String, Object>();

			m.put("id", cm.get("mnid"));
			m.put("text", cm.get("sno") + "." + cm.get("name"));
			boolean isParent = (Long) (cm.get("sic")) > 0;
			if (isParent)
				m.put("state", "closed");
			else
				m.put("state", "open");

			Map<String, Object> attrM = new HashMap<String, Object>();
			attrM.put("isParent", isParent);
			attrM.put("pmnid", cm.get("pmnid"));
			attrM.put("mtype", cm.get("mtype"));
			m.put("attributes", attrM);
			resultList.add(m);
		}
		return "1";
	}

	/**
	 * 按菜单ID查询菜单项
	 * 
	 * @author kansum
	 */
	public SysMenu getMenuByMnid(int mnid)
	{
		return (SysMenu) this.superDao.queryObject("system.getMenuByMnid", mnid);
	}

	/**
	 * 保存菜单项
	 * 
	 * @author kansum
	 */
	public String saveMenuItem(Map<String, String> menuItemMap)
	{
		SysMenu sysMenu = new SysMenu();
		try
		{
			BeanUtils.copyAnyProps(menuItemMap, sysMenu, null, true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		if (sysMenu.getMnid().intValue() == 0)
		{
			sysMenu.setMnid(null);
			sysMenu.setStatus(1);
			this.superDao.insertObject("manage.insertSysMenu", sysMenu);
		}
		else
		{
			Object obj = this.superDao.queryObject("system.getMenuByMnid", sysMenu.getMnid());
			if (obj != null)
			{
				this.superDao.updateObject("manage.updateSysMenu", sysMenu);
			}
		}
		return "OK";
	}

	/**
	 * 删除菜单项
	 * 
	 * @author kansum
	 */
	public String deleteMenuItem(int mnid)
	{
		List<?> qryLs = this.superDao.queryList("system.queryMenusByPmnid", mnid);
		if (CUtils.isNotEmpty(qryLs))
		{
			return "EXIST";
		}
		else
		{
			this.superDao.deleteObject("manage.deleteSysMenu", mnid);
			return "OK";
		}
	}

	/**
	 * 查询菜单关联的TAG
	 * 
	 * @author kansum
	 */
	public List<?> queryTagesByMnid(int mnid)
	{
		return this.superDao.queryList("manage.queryTagesByMnid", mnid);
	}

	/**
	 * 保存菜单标签的关联
	 * 
	 * @author kansum
	 */
	public String saveMenuTagsLink(Map<String, String> menuTagLinkMap)
	{
		int mnid = Integer.parseInt(menuTagLinkMap.get("mnid"));
		int tags = Integer.parseInt(menuTagLinkMap.get("tags"));

		List<TagMenu> tagMenuList = new ArrayList<TagMenu>();
		for (int i = 0; i < tags; i++)
		{
			TagMenu tagMenu = new TagMenu();
			tagMenu.setMnid(mnid);
			int tagid = Integer.parseInt(menuTagLinkMap.get("tagid_" + i));
			tagMenu.setTagid(tagid);
			int _v = CUtils.isInteger(menuTagLinkMap.get("sno_" + tagid)) ? Integer.parseInt(menuTagLinkMap.get("sno_" + tagid)) : 0;
			tagMenu.setSno(_v);
			_v = CUtils.isInteger(menuTagLinkMap.get("somp_" + tagid)) ? Integer.parseInt(menuTagLinkMap.get("somp_" + tagid)) : 0;
			tagMenu.setSomp(_v);
			String _nv = CUtils.isNotEmpty(menuTagLinkMap.get("tagShortName_" + tagid)) ? menuTagLinkMap.get("tagShortName_" + tagid) : null;
			tagMenu.setTagShortName(_nv);

			tagMenuList.add(tagMenu);
		}
		// 批量保存
		boolean ret = this.superDao.batchMenuTagsLinkSave(tagMenuList);
		return ret ? "OK" : "FAIL";
	}

	/**
	 * 删除菜单标签的关联
	 * 
	 * @author kansum
	 */
	public String deleteMenuTags(int mnid, String[] tagids)
	{
		List<TagMenu> tagMenuList = new ArrayList<TagMenu>();
		for (String tagid : tagids)
		{
			TagMenu tagMenu = new TagMenu();
			tagMenu.setMnid(mnid);
			tagMenu.setTagid(Integer.parseInt(tagid));
			tagMenuList.add(tagMenu);
		}
		boolean ret = this.superDao.batchMenuTagsLinkRemove(tagMenuList);
		return ret ? "OK" : "FAIL";
	}

	/**
	 * 删除TAG
	 * 
	 * @author kansum
	 */
	public String deleteTags(String[] tagids)
	{
		List<Integer> tagidList = new ArrayList<Integer>();
		for (String tagid : tagids)
		{
			TagMenu tagMenu = new TagMenu();
			tagMenu.setTagid(Integer.parseInt(tagid));
			Object ret = this.superDao.queryObject("manage.isTagMenuExist", tagMenu);
			if (Integer.parseInt(CUtils.toStr(ret)) > 0)
			{
				return "EXIST";
			}
			tagidList.add(tagMenu.getTagid());
		}
		this.superDao.deleteObject("manage.deleteTags", tagidList);
		return "OK";
	}

	/**
	 * 查询所有系统的配置项
	 * 
	 * @author kansum
	 */
	public String queryAllSysConfig(PageBean pageBean)
	{
		boolean ret = this.superDao.queryAllSysConfig(pageBean);
		return ret ? "OK" : "FAIL";
	}

	/**
	 * 保存系统配置项
	 * 
	 * @author kansum
	 */
	public String saveSysConfig(Map<String, String> cfgMap)
	{
		SysConfig config = new SysConfig();
		try
		{
			BeanUtils.copyAnyProps(cfgMap, config, null, true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		// 新增
		if (config.getC_id() == 0)
		{
			config.setC_id(null);
			config.setC_create_tm(new Date());
			this.superDao.insertObject("manage.insertSysConfig", config);
		}
		// 更新
		else
		{
			this.superDao.updateObject("manage.updateSysConfig", config);
		}
		return "OK";
	}

	/**
	 * 删除多条系统配置项
	 * 
	 * @author kansum
	 */
	public String deleteSysConfigs(String[] cids)
	{
		List<Integer> cidList = new ArrayList<Integer>();
		for (String cid : cids)
		{
			cidList.add(Integer.parseInt(cid));
		}
		this.superDao.deleteObject("manage.deleteSysConfigs", cidList);
		return "OK";
	}
}
